﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using System.Data;
using Newtonsoft.Json;
using Framework.DataAccess;
using Framework.Common.JsonEntities;
using Framework.Common;
using Framework.Common.Common;
using Mode;
using System.Text;

namespace WebSite.WebServer
{
    /// <summary>
    /// ExamRoom 的摘要说明
    /// </summary>
    public class ExamRoom : IHttpHandler, IRequiresSessionState
    {
        JsonReturnMessages msg;
        public void ProcessRequest(HttpContext context)
        {
            msg = new JsonReturnMessages();
            try
            {
                string action = context.Request.Params["Action"];
                if (action == "AddExam")
                    AddExam();
                else if (action == "ExamList")
                    GetExamList();
                else if (action == "SetExamStatus")
                    SetExamStatus();
                else if (action == "CandidateList")
                    GetCandidateList();
                else if (action == "CalcScore")
                    CalcScore();
                else if (action == "GetQATopic")
                    GetQATopic();
                else if (action == "ScoreQATopic")
                    ScoreQATopic();
                else if (action == "CandidateList2")
                    GetCandidateList2();
                else if (action == "UserExam")
                    UserExamList();
                else if (action == "ReExamRoom")
                    ReExamRoom();
                else if (action == "delexam")
                    DeleteExam();
                else if (action == "chart")
                    ExamChart();
                else if (action == "userchart")
                    UserChart();
            }
            catch (Exception err)
            {
                var message = err.Message;
                if (err.InnerException != null && err.InnerException.Message != null)
                    message += "<BR>" + err.InnerException.Message;

                msg.IsSuccess = 0;
                msg.Msg = message;

                var json = JsonConvert.SerializeObject(msg);
                context.Response.Write(json);
            }
            context.Response.End();
        }

        /// <summary>
        /// 检查是否登录
        /// </summary>
        /// <returns></returns>
        private loginInfo chklogin()
        {
            try
            {
                return SessionShard.loginUser;
            }
            catch
            {
                msg.IsSuccess = -9;
                msg.Msg = "登陆失效，请重新登陆!";
                return null;
            }
        }



        /// <summary>
        /// 创建考场
        /// </summary>
        private void AddExam()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }
            string str = context.Request.Params["ExamData"];
            examination_table examData = JsonConvert.DeserializeObject<examination_table>(str);
            examData.date = System.DateTime.Now;
            examData.status = 0;
            examinationDA myExam = new examinationDA();
            int examID = myExam.AddExam(examData);

            email e = new email(examID);
            e.SendMail();

            msg.Data = examID;
            msg.IsSuccess = (examID > 0 ? 1 : 0);
            var json = JsonConvert.SerializeObject(msg);
            context.Response.Write(json);
        }

        /// <summary>
        /// 查询考场列表
        /// </summary>
        private void GetExamList()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }

            examinationDA myExam = new examinationDA();

            int areID = context.Request.Params["areID"].ToInt();
            int modelID = context.Request.Params["modelID"].ToInt();
            string name = context.Request.Params["name"].ToStr();
            int status = context.Request.Params["status"].ToInt();
            DateTime? beginDate = context.Request.Params["beginDate"].ToDateNull();
            DateTime? endDate = context.Request.Params["endDate"].ToDateNull();

            PageView pageInfo = new PageView();
            pageInfo.PageIndex = context.Request.Params["page"].ToInt(1);
            pageInfo.PageSize = context.Request.Params["pagesize"].ToInt(20);
            pageInfo.SortName = context.Request.Params["sortname"].ToStr();
            pageInfo.SortOrder = context.Request.Params["sortorder"].ToStr();
            pageInfo.SearchParams = context.Request.Params;

            PageList<object> List = myExam.GetExamList(pageInfo, areID, modelID, status, name, beginDate, endDate);

            string Rjson = @"{""Rows"":null,""Total"":""0""}";
            if (List.Data != null)
            {
                Rjson = @"{""Rows"":" + List.Data.ToJson() + @",""Total"":""" + List.Total + @"""}";
            }
            context.Response.Write(Rjson);
        }

        /// <summary>
        /// 设置考场状态
        /// </summary>
        public void SetExamStatus()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }
            int examID = context.Request.Params["ExamID"].ToInt(0);
            int status = context.Request.Params["Status"].ToInt(0);
            examinationDA myExam = new examinationDA();
            bool succFlag = myExam.SetExamStatus(examID, status);
            if (succFlag)
                msg.IsSuccess = 1;
            var json = JsonConvert.SerializeObject(msg);
            context.Response.Write(json);
        }

        /// <summary>
        /// 根据考场ID获取考生列表
        /// </summary>
        public void GetCandidateList()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }
            int examID = context.Request.Params["ExamID"].ToInt(0);
            examinationDA myExam = new examinationDA();
            PageView pageInfo = new PageView();
            pageInfo.PageIndex = context.Request.Params["page"].ToInt(1);
            pageInfo.PageSize = context.Request.Params["pagesize"].ToInt(20);
            pageInfo.SortName = context.Request.Params["sortname"].ToStr();
            pageInfo.SortOrder = context.Request.Params["sortorder"].ToStr();
            pageInfo.SearchParams = context.Request.Params;

            PageList<object> List = myExam.GetCandidateList(pageInfo, examID);

            string Rjson = @"{""Rows"":null,""Total"":""0""}";
            if (List.Data != null)
            {
                Rjson = @"{""Rows"":" + List.Data.ToJson() + @",""Total"":""" + List.Total + @"""}";
            }
            context.Response.Write(Rjson);
        }
        /// <summary>
        /// 根据考生ID获取考场列表
        /// </summary>
        void GetCandidateList2()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }

            DateTime? beginDate = context.Request.Params["beginDate"].ToDateNull();
            DateTime? endDate = context.Request.Params["endDate"].ToDateNull();

            examinationDA myExam = new examinationDA();
            PageView pageInfo = new PageView();
            pageInfo.PageIndex = context.Request.Params["page"].ToInt(1);
            pageInfo.PageSize = context.Request.Params["pagesize"].ToInt(20);
            pageInfo.SortName = context.Request.Params["sortname"].ToStr();
            pageInfo.SortOrder = context.Request.Params["sortorder"].ToStr();
            pageInfo.SearchParams = context.Request.Params;

            PageList<object> List = myExam.GetCandidateList2(pageInfo, loginUser.M_ID,beginDate,endDate);

            string Rjson = @"{""Rows"":null,""Total"":""0""}";
            if (List.Data != null)
            {
                Rjson = @"{""Rows"":" + List.Data.ToJson() + @",""Total"":""" + List.Total + @"""}";
            }
            context.Response.Write(Rjson);
        }

        /// <summary>
        /// 阅卷
        /// </summary>
        public void CalcScore()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }
            //考生ID
            int cID = context.Request.Params["C_ID"].ToInt(0);
            ReadOver myObj = new ReadOver(cID);
            myObj.ReadTopic();
            msg.IsSuccess = 1;
            var json = JsonConvert.SerializeObject(msg);
            context.Response.Write(json);
        }

        /// <summary>
        /// 获取问答题阅卷列表
        /// </summary>
        public void GetQATopic()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }
            //考生ID
            int cID = context.Request.Params["C_ID"].ToInt(0);
            ReadOver myObj = new ReadOver(cID);
            List<sheet_query_view> list = myObj.GetQueryTopic();
            foreach (sheet_query_view item in list)
                if (string.IsNullOrEmpty(item.A_ANSWER))
                    item.A_ANSWER = "";
            string jsonStr = list.ToJson();
            context.Response.Write(jsonStr);
        }

        /// <summary>
        /// 问答题评分
        /// </summary>
        public void ScoreQATopic()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }
            //考生ID
            int cID = context.Request.Params["C_ID"].ToInt(0);
            string str = context.Request.Params["TopicScores"];
            List<sheetReplay_score> scoreList = JsonConvert.DeserializeObject<List<sheetReplay_score>>(str);
            examinationDA myExam = new examinationDA();
            myExam.ScoreQATopic(cID, scoreList);
            msg.IsSuccess = 1;
            var json = JsonConvert.SerializeObject(msg);
            context.Response.Write(json);
        }


        void UserExamList() {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null){
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }

            int userid = context.Request.Params["userid"].ToInt();
            int page = context.Request.Params["page"].ToInt();
            int pagesize = context.Request.Params["pagesize"].ToInt();
            string sortname = context.Request.Params["sortname"].ToString();
            string sortorder = context.Request.Params["sortorder"].ToString();

            examinationDA eda = new examinationDA();
            PageList<object> result = eda.GetUserExamList(userid, page, pagesize, sortname, sortorder);
            string Rjson = @"{""Rows"":null,""Total"":""0""}";
            if (result.Data != null)
            {
                Rjson = @"{""Rows"":" + result.Data.ToJson() + @",""Total"":""" + result.Total + @"""}";
            }
            context.Response.Write(Rjson);
        }


        void ReExamRoom() {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }

            int candidateid = context.Request.Params["candidateid"].ToInt();
            int userid = context.Request.Params["userid"].ToInt();

            examinationDA eda = new examinationDA();
            msg.IsSuccess = eda.ReExamRoom(candidateid,userid);

            context.Response.Write(JsonConvert.SerializeObject(msg));
        }

        void DeleteExam() {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }

            int examid = context.Request.Params["examid"].ToInt();
            examinationDA eda = new examinationDA();
            msg.IsSuccess = eda.DeleteExamRoom(examid);

            context.Response.Write(JsonConvert.SerializeObject(msg));
        }


        void ExamChart() {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }

            int examid = context.Request.Params["examid"].ToInt();
            examinationDA eda = new examinationDA();
            msg.IsSuccess = 1;
            msg.Data = eda.ExamChart(examid);
            context.Response.Write(JsonConvert.SerializeObject(msg));
        }

        void UserChart() {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }

            int userid = context.Request.Params["userid"].ToInt();
            examinationDA eda = new examinationDA();
            msg.IsSuccess = 1;
            msg.Data = eda.UserExamChart(userid);
            context.Response.Write(JsonConvert.SerializeObject(msg));
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}